package com.classic.base;

import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.classic.content.contents;
import com.classic.duanzhi.DZDataBen1;
import com.classic.duanzhi.R;
import com.classic.utils.helper;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public abstract class BaseListFragment1 extends LazyLoadFragment  {
    private RefreshLayout refreshLayout;         //刷新控件
    private int pagerNumber = 1;                //当前页面数据页码
    private LinearLayout empty;                  //空页面布局
    private FrameLayout bannerContainer;                  //Banner

    private List<DZDataBen1> mListData = new ArrayList<>();// 当前页面总数据
    public boolean isRefresh = true;            //是否是在刷新中
    private CustomAdapter mAdapter;             //列表适配器
    private List<View> mAdViewList = new ArrayList<>();                  //保存广告数据
    private HashMap<View, Integer> mAdViewPositionMap = new HashMap<>(); //保存广告对应的列表数据

    @Override
    public void fetchData() {
        refreshLayout.autoRefresh();
    }

    @Override
    protected void initView() {
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        RecyclerView mRecyclerView = rootView.findViewById(R.id.listView);
        empty = rootView.findViewById(R.id.ll_empty);
        bannerContainer = rootView.findViewById(R.id.bannerContainer);

        mAdapter = new CustomAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAdapter);
        //刷新
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                initNativeExpressAD();
                initData(1);
            }
        });
        //加载更多
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                initData(pagerNumber + 1);
//                boolean b = pagerNumber % 5 == 0;
//                Log.d("---------", b + "");
            }

        });
    }

    @Override
    protected void initData() {

    }

    /**
     * @param number 页码
     * @return 请求接口
     */
    private String getUrl(String number) {
        return contents.url + getUrlInfo() + number + ".html";
    }

    /**
     * 获取url关键字字段
     *
     * @return 接口关键字
     */
    protected abstract String getUrlInfo();

    /**
     * @param number 页码
     *               请求数据方法
     */
    void initData(final int number) {
        isRefresh = false;
        new Thread() {
            @Override
            public void run() {
                Document doc;
                try {
                    doc = Jsoup.connect(getUrl(String.valueOf(number))).get();
                    Elements elementsByClass = doc.getElementsByClass("preview");
                    Elements info = doc.getElementsByClass("info");
                    Elements newslist = doc.getElementsByClass("newslist");
                    Elements target = newslist.select("dt");
                    final List<DZDataBen1> dataBens = new ArrayList<>();
                    for (int i = 0; i < elementsByClass.size(); i++) {
                        Element span = info.get(i).select("span").get(1);
                        DZDataBen1 dataBen = new DZDataBen1(target.get(i).text(),
                                elementsByClass.get(i).text(), span.text(),
                                info.get(i).select("a").attr("href"));
                        dataBens.add(dataBen);
                    }
                    if (null == getActivity()) return;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            pagerNumber = number;
                            if (pagerNumber == 1) {
                                mListData = dataBens;
                            } else {
                                mListData.addAll(dataBens);
                            }
                            if (dataBens.size() < 10) {
                                refreshLayout.setEnableLoadMore(false);
                                if (pagerNumber != 1) {
                                    showTT("没有更多了");
                                }
                            } else {
                                refreshLayout.setEnableLoadMore(true);
                            }
                            if (dataBens.size() == 0 && pagerNumber == 1) {
                                empty.setVisibility(View.VISIBLE);
                            } else {
                                empty.setVisibility(View.GONE);
                            }
                            mAdapter.setNotifyDataSetChanged();
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                            isRefresh = true;
                        }
                    });
                } catch (IOException e) {
                    if (getActivity() == null) return;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showTT("网络信号不好,请检查网络！");
                            mAdapter.setNotifyDataSetChanged();
                            if (pagerNumber == 1 && mListData.size() == 0) {
                                empty.setVisibility(View.VISIBLE);
                            } else {
                                empty.setVisibility(View.GONE);
                            }
                            refreshLayout.finishRefresh();
                            refreshLayout.finishLoadMore();
                            isRefresh = true;
                        }
                    });
                }
            }
        }.start();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // 使用完了每一个NativeExpressADView之后都要释放掉资源。
    }


    /**
     * 请求广告
     */
    private void initNativeExpressAD() {
    }



    public String title;
    public String getTitle() {
        return title;
    }

    /**
     * RecyclerView的Adapter
     */
    class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {

        static final int TYPE_DATA = 0;
        static final int TYPE_AD = 1;
        private List<Object> mData = new ArrayList<>();
        private List<View> ADData = new ArrayList<>();

        CustomAdapter() {
            this.mData = new ArrayList<>();
            this.ADData = new ArrayList<>();
        }

        public void setNotifyDataSetChanged() {
            mData = new ArrayList<>();
            mData.addAll(mListData);
            notifyDataSetChanged();
        }




        @Override
        public int getItemCount() {
            if (mData != null) {
                return mData.size();
            } else {
                return 0;
            }
        }

        @Override
        public int getItemViewType(int position) {
            return mData.get(position) instanceof View ? TYPE_AD : TYPE_DATA;
        }

        @Override
        public void onBindViewHolder(@NonNull final CustomAdapter.CustomViewHolder holder, final int position) {
            int type = getItemViewType(position);
            if (TYPE_AD == type) {
                final View adView = (View) mData.get(position);
                mAdViewPositionMap.put(adView, position); // 广告在列表中的位置是可以被更新的
                if (holder.container.getChildCount() > 0 && holder.container.getChildAt(0) == adView) {
                    return;
                }
                Log.d("position ----- ", "----------" + position);
                if (holder.container.getChildCount() > 0) {
                    holder.container.removeAllViews();
                }
                if (adView.getParent() != null) {
                    ((ViewGroup) adView.getParent()).removeView(adView);
                }

                holder.container.addView(adView);
            } else {
                final DZDataBen1 o = (DZDataBen1) mData.get(position);
                holder.time.setText(o.getDate());
                holder.week.setText(helper.getWeek(o.getDate()));
                holder.sub.setText(o.getContent());
                holder.tvTitle.setText( o.getTitle());
            }
        }

        @NonNull
        @Override
        public CustomAdapter.CustomViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
            int layoutId = (viewType == TYPE_AD) ? R.layout.ad_item_express_ad : R.layout.ad_item_anepisode_layout;
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(layoutId, null);
            return new CustomViewHolder(view);
        }

        void setADData(List<View> ADData) {
            this.ADData.addAll(ADData);
//            setData(mData);
        }

        class CustomViewHolder extends RecyclerView.ViewHolder {
            TextView title, week, sub, time,tvTitle,details;
            public ViewGroup container;

            CustomViewHolder(View view) {
                super(view);
                title = view.findViewById(R.id.title);
                container = view.findViewById(R.id.express_ad_container);

                time = view.findViewById(R.id.tv_time);
                tvTitle = view.findViewById(R.id.tv_title);
                details = view.findViewById(R.id.tv_details);
                week = view.findViewById(R.id.tv_week);
                sub = view.findViewById(R.id.tv_subtitle);
            }
        }
    }

}
